#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
迭代式关键词搜索演示脚本
展示多轮搜索、关键词扩展、话题提取等功能
"""

import sys
import os
import time

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from src.utils import load_config, setup_logging
from src.iterative_searcher import create_iterative_searcher


def run_iterative_search_demo():
    """运行迭代式搜索演示"""
    print("🚀 迭代式关键词搜索演示")
    print("=" * 60)
    
    try:
        # 加载配置
        config = load_config()
        logger = setup_logging(config)
        
        # 创建迭代式搜索器
        searcher = create_iterative_searcher(config)
        
        # 种子关键词
        seed_keywords = ["朋友圈"]
        print(f"📝 种子关键词: {seed_keywords}")
        print()
        
        # 显示初始统计
        print("📊 初始统计:")
        initial_stats = searcher.get_search_statistics()
        for key, value in initial_stats.items():
            print(f"  {key}: {value}")
        print()
        
        # 运行迭代式搜索
        print("🔄 开始迭代式搜索...")
        start_time = time.time()
        
        final_stats = searcher.run_iterative_search(seed_keywords)
        
        end_time = time.time()
        duration = end_time - start_time
        
        # 显示最终结果
        print("\n" + "=" * 60)
        print("🎉 迭代式搜索完成！")
        print("=" * 60)
        
        print(f"⏱️  总耗时: {duration:.2f} 秒")
        print(f"🔄 搜索轮数: {final_stats['total_rounds']}")
        print(f"📚 发现话题: {final_stats['total_topics']} 个")
        print(f"🔑 发现关键词: {final_stats['total_keywords']} 个")
        print(f"🌱 种子关键词: {final_stats['seed_keywords']} 个")
        print(f"📈 扩展关键词: {final_stats['expanded_keywords']} 个")
        print(f"📊 最终话题库: {final_stats['final_topic_count']} 个")
        print(f"📊 最终关键词库: {final_stats['final_keyword_count']} 个")
        
        # 显示当前统计
        print("\n📊 当前统计:")
        current_stats = searcher.get_search_statistics()
        for key, value in current_stats.items():
            print(f"  {key}: {value}")
        
        # 清理资源
        searcher.cleanup()
        
        print("\n✅ 演示完成！")
        
    except Exception as e:
        print(f"\n❌ 演示执行失败: {e}")
        import traceback
        traceback.print_exc()


def show_database_info():
    """显示数据库信息"""
    print("\n🗄️  数据库信息:")
    print("=" * 40)
    
    try:
        config = load_config()
        logger = setup_logging(config)
        
        from src.database import create_database_manager
        
        db_manager = create_database_manager(config)
        
        # 显示数据库统计
        topic_count = db_manager.get_topic_count()
        keyword_count = db_manager.get_keyword_count()
        processed_count = db_manager.get_keyword_count(processed_only=True)
        
        print(f"📚 话题总数: {topic_count}")
        print(f"🔑 关键词总数: {keyword_count}")
        print(f"✅ 已处理关键词: {processed_count}")
        print(f"⏳ 未处理关键词: {keyword_count - processed_count}")
        
        # 关闭连接
        db_manager.close()
        
    except Exception as e:
        print(f"❌ 获取数据库信息失败: {e}")


def show_configuration():
    """显示配置信息"""
    print("\n⚙️  配置信息:")
    print("=" * 40)
    
    try:
        config = load_config()
        
        # 数据库配置
        db_config = config.get('database', {})
        print("🗄️  数据库配置:")
        print(f"  PostgreSQL: {db_config.get('postgres', {}).get('host', 'localhost')}:{db_config.get('postgres', {}).get('port', 5432)}")
        print(f"  Redis: {db_config.get('redis', {}).get('host', 'localhost')}:{db_config.get('redis', {}).get('port', 6379)}")
        
        # 迭代搜索配置
        search_config = config.get('iterative_search', {})
        print("\n🔄 迭代搜索配置:")
        print(f"  最大轮数: {search_config.get('max_rounds', 5)}")
        print(f"  批处理大小: {search_config.get('batch_size', 100)}")
        print(f"  最大进程数: {search_config.get('max_processes', 4)}")
        print(f"  轮次间延迟: {search_config.get('delay_between_rounds', 2.0)} 秒")
        print(f"  关键词长度范围: {search_config.get('min_keyword_length', 2)} - {search_config.get('max_keyword_length', 50)}")
        
    except Exception as e:
        print(f"❌ 获取配置信息失败: {e}")


def main():
    """主函数"""
    print("🎯 迭代式关键词搜索系统")
    print("=" * 60)
    
    try:
        # 显示配置信息
        show_configuration()
        
        # 显示数据库信息
        show_database_info()
        
        # 运行演示
        run_iterative_search_demo()
        
        print("\n💡 使用说明:")
        print("  1. 确保PostgreSQL和Redis服务已启动")
        print("  2. 在config/config.yaml中配置数据库连接信息")
        print("  3. 调整迭代搜索参数以满足需求")
        print("  4. 运行 python iterative_search_demo.py 开始搜索")
        
    except Exception as e:
        print(f"\n❌ 程序执行失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
